//
//  CZMainTabBar.swift
//  czbkiosweibo5
//
//  Created by zhangping on 15/10/12.
//  Copyright © 2015年 zhangping. All rights reserved.
//

import UIKit

class CZMainTabBar: UITabBar {
    
    // MARK: - 属性
    private let buttonCount = 5
    
    // MARK: - 生命周期方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        print("CZMainTabBar")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 计算单个item的frame
        let width = bounds.width / CGFloat(buttonCount)
        let itemFrame = CGRect(x: 0, y: 0, width: width, height: bounds.height)
        
        var index = 0
        // 重新布局系统的UITabBarButton.
        for subView in self.subviews {
            if subView is UIControl && !(subView is UIButton) {
                print("subView: \(subView)")
                // 计算每个item的位置
                subView.frame = CGRectOffset(itemFrame, CGFloat(index) * width, 0)
                
                index += (index == 1) ? 2 : 1
            }
        }
        
        composeButton.frame = CGRectOffset(itemFrame, 2 * width, 0)
        
        print("-------")
    }
    
    // MARK: - 懒加载
    lazy var composeButton: UIButton = {
        let button = UIButton()
        
        // 按钮图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        // 按钮背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        self.addSubview(button)
        return button
    }()
}
